package com.zhouxiaoge.axis;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.xml.namespace.QName;
import java.io.File;
import java.io.IOException;

public class WebServiceRPC {

    private static final String WSDL = "http://localhost:8080/Service/Hello";
    private static final String NAMESPACE = "http://service.ws.sample";
    private static final String METHODSTR = "sayHello";
    private String filePath = System.getProperty("user.dir") + "\\src\\test\\resources\\reqxml.txt";

    private String xml = "";
    private RPCServiceClient client;
    private Options options;
    private String responseText = "";


    @Before
    public void preparatoryWork() throws IOException {
        xml = FileUtils.readFileToString(new File(filePath), "GBK");
        //使用RPC调用webService
        client = new RPCServiceClient();
        EndpointReference targetEPR = new EndpointReference(WSDL);
        options = client.getOptions();
        options.setTo(targetEPR);
    }

    @Test
    public void webServcieTest() throws Exception {

        Object[] response = client.invokeBlocking(new QName(NAMESPACE, METHODSTR), new Object[]{xml}, new Class[]{String.class});
        responseText = (String) response[0];

    }

    @Test
    public void testRPCClient4Parameters() {
        try {
            options.setAction("urn:SayHello");

            // 指定getPrice方法的参数值
            String[] parameters = new String[]{"myname"};
            String[] value = new String[]{xml};

            // 指定getPrice方法返回值的数据类型的Class对象
            OMFactory omFactory = OMAbstractFactory.getOMFactory();
            // 设置命名空间
            OMNamespace omNamespace = omFactory.createOMNamespace(NAMESPACE, "");
            OMElement omElement = omFactory.createOMElement(METHODSTR, omNamespace);

            for (int i = 0; i < parameters.length; i++) {
                QName qName = new QName(parameters[i]);
                OMElement inner = omFactory.createOMElement(qName);
                inner.setText(value[i]);
                omElement.addChild(inner);
            }

            OMElement omElement1 = client.sendReceive(omElement);
            System.out.println(omElement1.getFirstElement().getText());
            responseText = omElement1.getFirstElement().getText();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void finshWork() throws IOException {
        System.out.println(responseText);
        String respPath = filePath.replace(filePath, "resp.txt");
        FileUtils.writeStringToFile(new File(respPath), responseText);
    }

}
